<script setup>
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const loginType = ref('user') // user 或 admin
const username = ref('')
const password = ref('')
const remember = ref(false)
const loading = ref(false)
const errorMessage = ref('')

// 获取重定向路径，如果没有则根据用户类型决定
const redirectPath = computed(() => {
  if (route.query.redirect) return route.query.redirect
  return loginType.value === 'admin' ? '/admin/dashboard' : '/'
})

// 验证用户名是否为纯数字
const validateUsername = () => {
  if (!username.value) {
    return false
  }
  
  if (loginType.value === 'user' && !/^[0-9]+$/.test(username.value)) {
    errorMessage.value = '用户名必须是纯数字'
    return false
  }
  
  return true
}

const handleLogin = async () => {
  // 清除之前的错误信息
  errorMessage.value = ''
  
  // 验证输入
  if (!username.value || !password.value) {
    errorMessage.value = '请输入用户名和密码'
    return
  }
  
  // 验证用户名格式
  if (!validateUsername()) {
    return
  }
  
  try {
    loading.value = true
    
    const credentials = {
      loginName: username.value,  // 修改为与后端匹配的参数名
      password: password.value,
      remember: remember.value
    }
    
    if (loginType.value === 'user') {
      const result = await authStore.login(credentials)
      if (result.success) {
        router.push(redirectPath.value)
      } else {
        errorMessage.value = result.message || '登录失败，请检查您的凭据'
      }
    } else {
      const result = await authStore.adminLogin(credentials)
      if (result.success) {
        router.push('/admin/dashboard')
      } else {
        errorMessage.value = result.message || '管理员登录失败，请检查您的凭据'
      }
    }
  } catch (error) {
    console.error('Login error:', error)
    errorMessage.value = error.response?.data?.message || '登录失败，请检查您的凭据'
  } finally {
    loading.value = false
  }
}

const switchLoginType = (type) => {
  loginType.value = type
  errorMessage.value = ''
}
</script>

<template>
  <div class="login-page">
    <div class="login-container card">
      <div class="login-header">
        <h1 class="login-title">博客系统</h1>
        <div class="login-tabs">
          <button 
            :class="['login-tab', { active: loginType === 'user' }]" 
            @click="switchLoginType('user')"
          >
            用户登录
          </button>
          <button 
            :class="['login-tab', { active: loginType === 'admin' }]" 
            @click="switchLoginType('admin')"
          >
            管理员登录
          </button>
        </div>
      </div>
      
      <form class="login-form" @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username" class="form-label">用户名</label>
          <input 
            id="username" 
            v-model="username"
            type="text" 
            class="form-input" 
            :placeholder="loginType === 'user' ? '请输入数字用户名' : '请输入用户名'"
            required
            autocomplete="username"
          />
          <small v-if="loginType === 'user'" class="form-hint">用户名必须是纯数字</small>
        </div>
        
        <div class="form-group">
          <label for="password" class="form-label">密码</label>
          <input 
            id="password" 
            v-model="password"
            type="password" 
            class="form-input" 
            placeholder="请输入密码"
            required
            autocomplete="current-password"
          />
        </div>
        
        <div class="form-options">
          <label class="checkbox-label">
            <input type="checkbox" v-model="remember" />
            <span class="checkbox-text">记住我</span>
          </label>
          <a href="#" class="forgot-password">忘记密码?</a>
        </div>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <button 
          type="submit" 
          class="btn btn-primary login-btn" 
          :disabled="loading"
        >
          <span v-if="loading" class="loading-spinner-small"></span>
          <span v-else>登录</span>
        </button>
      </form>
      
      <div class="login-footer">
        <p>
          还没有账号? 
          <router-link to="/register" class="register-link">立即注册</router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<style>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  background-color: var(--background-color);
}

.login-container {
  max-width: 450px;
  width: 100%;
  padding: 2.5rem;
}

.login-header {
  margin-bottom: 2rem;
  text-align: center;
}

.login-title {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 1.5rem;
  color: var(--primary-color);
}

.login-tabs {
  display: flex;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 1.5rem;
}

.login-tab {
  flex: 1;
  background: none;
  border: none;
  padding: 1rem;
  font-size: 1rem;
  font-weight: 500;
  color: var(--text-light);
  cursor: pointer;
  transition: color 0.2s;
  position: relative;
}

.login-tab.active {
  color: var(--primary-color);
}

.login-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: var(--primary-color);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-label input {
  margin-right: 0.5rem;
}

.checkbox-text {
  font-size: 0.9rem;
  color: var(--text-light);
}

.forgot-password {
  font-size: 0.9rem;
  color: var(--text-light);
}

.forgot-password:hover {
  color: var(--primary-color);
}

.login-btn {
  width: 100%;
  margin-top: 1rem;
  padding: 0.75rem;
}

.login-footer {
  margin-top: 2rem;
  text-align: center;
  color: var(--text-light);
  font-size: 0.9rem;
}

.register-link {
  font-weight: 600;
}

.form-hint {
  font-size: 0.8rem;
  color: var(--text-light);
  margin-top: 0.25rem;
  display: block;
}

.error-message {
  background-color: rgba(217, 83, 79, 0.1);
  color: var(--error-color);
  padding: 0.75rem;
  border-radius: 4px;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.loading-spinner-small {
  display: inline-block;
  width: 1rem;
  height: 1rem;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
  margin-right: 0.5rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 576px) {
  .login-container {
    padding: 2rem 1.5rem;
  }
}
</style> 